
//
//  IntegralGoodsViewController.m
//  cm
//
//  Created by N-X on 2018/2/3.
//  Copyright © 2018年 feihu. All rights reserved.
//

#import "IntegralGoodsViewController.h"
#import "ImagePlayerView.h"
#import <WebKit/WebKit.h>
#import "PurchaseViewController.h"
#import "BaseNavigationController.h"
#import "LoginViewController.h"

#define tabBarHeight  self.tabBarController.tabBar.frame.size.height

@interface IntegralGoodsViewController()<ImagePlayerViewDelegate,WKNavigationDelegate>

@property (nonatomic,strong) ImagePlayerView *imagePlayerView;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, assign) CGFloat delayTime;
@property (nonatomic, assign) CGFloat contentHeight;

@end

@implementation IntegralGoodsViewController
{
    UIView *headView;
    NSArray *imageArr;
    UILabel *priceLabel;
    UILabel *freightLabel;
    UILabel *titleLabel;
    UILabel *detailLabel;
    MBProgressHUD *HUD;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createGoodsView];
}

-(void)createGoodsView
{
    _scrollView = [[UIScrollView  alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-tabBarHeight)];
    _scrollView.contentSize = CGSizeMake(0, kScreenHeight);
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);
    [self.view addSubview:_scrollView];
    
    [self createHeadView];
    
    NSInteger count = 1;
    for (NSInteger i = 0; i < count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:i == 0?@"立即购买":@"立即购买" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        button.tag = 100 + i;
        button.backgroundColor = i == 0?[UIColor colorWithRed:0.64 green:0.8 blue:0.99 alpha:1]:[UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        button.sd_layout
        .leftSpaceToView(self.view, i*kScreenWidth/count)
        .bottomSpaceToView(self.view, 0)
        .widthIs(kScreenWidth/count)
        .heightIs(45);
    }
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.mode = MBProgressHUDModeText;
    [self.view addSubview:HUD];
}

-(void)buttonClick:(UIButton *)button
{
    if (![[mUserDefaults objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            BaseNavigationController *navController = [[BaseNavigationController alloc] initWithRootViewController:[LoginViewController new]];
            [mAppDelegate.window.rootViewController presentViewController:navController animated:YES completion:nil];
        });
        return;
    }
    
    PurchaseViewController *purchaseVC = [[PurchaseViewController alloc] init];
    purchaseVC.dataSource = [NSMutableArray arrayWithObject:self.dataSource];
    purchaseVC.type = 2;
    [self.navigationController pushViewController:purchaseVC animated:YES];
}

-(void)createHeadView
{
    headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth + 60)];
    headView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:headView];
    
    _imagePlayerView = [[ImagePlayerView alloc] init];
    _imagePlayerView.scrollInterval = 5.0f;
    _imagePlayerView.hidePageControl = NO;
    _imagePlayerView.pageControlPosition = ICPageControlPosition_BottomCenter;
    [headView addSubview:_imagePlayerView];
    _imagePlayerView.sd_layout
    .topSpaceToView(headView, 0)
    .leftSpaceToView(headView, 0)
    .widthIs(kScreenWidth)
    .heightIs(kScreenWidth-50);
    imageArr = @[self.dataSource[@"imgUrl"]];
    [_imagePlayerView initWithCount:imageArr.count delegate:self];
    //    _imagePlayerView.backgroundColor = [UIColor redColor];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, statusBarRect.size.height, 40, 44);
    [backBtn setImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:backBtn];
    
    titleLabel = [[UILabel alloc] init];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.numberOfLines = 2;
    titleLabel.textColor = [UIColor blackColor];
    [headView addSubview:titleLabel];
    titleLabel.sd_layout
    .topSpaceToView(_imagePlayerView, 5)
    .leftSpaceToView(headView, 15)
    .widthIs(kScreenWidth - 30)
    .heightIs(50);
    titleLabel.text = self.dataSource[@"productName"];
    
    priceLabel = [[UILabel alloc] init];
    priceLabel.font = [UIFont systemFontOfSize:14];
    priceLabel.textColor = [UIColor colorWithRed:0.99 green:0.28 blue:0.1 alpha:1];
    [headView addSubview:priceLabel];
    priceLabel.sd_layout
    .topSpaceToView(titleLabel, 0)
    .leftSpaceToView(headView, 15)
    .widthIs(kScreenWidth - 30)
    .heightIs(20);
    priceLabel.text = [NSString stringWithFormat:@"首付价¥%@",self.dataSource[@"downPayment"]];
    priceLabel.hidden = YES;
    
    freightLabel = [[UILabel alloc] init];
    freightLabel.text = [NSString stringWithFormat:@"积分%@",self.dataSource[@"points"]];
    freightLabel.font = [UIFont systemFontOfSize:13];
    freightLabel.textColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1];
    [headView addSubview:freightLabel];
    freightLabel.sd_layout
    .topSpaceToView(priceLabel, 0)
    .leftSpaceToView(headView, 15)
    .widthIs(kScreenWidth - 30)
    .heightIs(20);
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [headView addSubview:line];
    line.sd_layout
    .bottomSpaceToView(headView, 5)
    .leftSpaceToView(headView, 0)
    .widthIs(kScreenWidth)
    .heightIs(5);
    
    detailLabel = [[UILabel alloc] init];
    detailLabel.textAlignment = NSTextAlignmentCenter;
    detailLabel.font = [UIFont systemFontOfSize:13];
    detailLabel.text = @"商品详情";
    detailLabel.textColor = [UIColor colorWithRed:0.62 green:0.62 blue:0.62 alpha:1];
    [_scrollView addSubview:detailLabel];
    detailLabel.sd_layout
    .topSpaceToView(headView, 5)
    .leftSpaceToView(_scrollView, 50)
    .widthIs(kScreenWidth - 100)
    .heightIs(20);
    
    UIView *bottomline = [[UIView alloc] init];
    bottomline.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [_scrollView addSubview:bottomline];
    bottomline.sd_layout
    .topSpaceToView(detailLabel, 5)
    .leftSpaceToView(_scrollView, 50)
    .widthIs(kScreenWidth - 100)
    .heightIs(1);
    
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(10, 0, kScreenWidth, 1) configuration:wkWebConfig];
    self.webView.navigationDelegate = self;
    self.webView.opaque = NO;
    self.webView.backgroundColor = [UIColor clearColor];
    [_scrollView addSubview:self.webView];
    [self.webView loadHTMLString:self.dataSource[@"content"] baseURL:nil];
    
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, 2)];
    [self.view addSubview:self.progressView];
    self.progressView.progressTintColor = [UIColor colorWithRed:0.99 green:0.5 blue:0.18 alpha:1];
    self.progressView.trackTintColor = [UIColor clearColor];
    
    // KVO 监听属性，除了下面列举的两个，还有其他的一些属性，具体参考 WKWebView 的头文件
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    // 监听 self.webView.scrollView 的 contentSize 属性改变，从而对底部添加的自定义 View 进行位置调整
    [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    [_scrollView addSubview:_webView];
    _webView.sd_layout
    .topSpaceToView(detailLabel, 10)
    .leftSpaceToView(_scrollView, 10)
    .widthIs(kScreenWidth-20)
    .heightIs(100);
}

-(void)backBtnClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
        }
        else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
    }
    else if ([keyPath isEqualToString:@"contentSize"]) {
        if (self.contentHeight != self.webView.scrollView.contentSize.height) {
            self.contentHeight = self.webView.scrollView.contentSize.height;
            self.webView.sd_layout
            .topSpaceToView(detailLabel, 10)
            .leftSpaceToView(_scrollView, 10)
            .widthIs(kScreenWidth-20)
            .heightIs(self.contentHeight);
            [_scrollView setupAutoContentSizeWithBottomView:self.webView bottomMargin:10];
            NSLog(@"contentHeight:%f", self.contentHeight);
        }
    }
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"webViewDidFinishLoad");
    //    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'" completionHandler:^(id _Nullable textColor, NSError * _Nullable error) {
    //        NSLog(@"%@",textColor);
    //    }];
}

-(void)conversionBtnHandler
{
    //    ConfirmViewController *confirmVC = [[ConfirmViewController alloc] init];
    //    confirmVC.dataSource = dataSource;
    //    [self.navigationController pushViewController:confirmVC animated:YES];
}

#pragma mark - ImagePlayerViewDelegate
- (NSInteger)numberOfItems:(ImagePlayerView *)imagePlayerView
{
    return imageArr.count;
}

- (void)imagePlayerView:(ImagePlayerView *)imagePlayerView loadImageForImageView:(UIImageView *)imageView index:(NSInteger)index
{
    if (imageArr && imageArr.count > index) {
        [imageView sd_setImageWithURL:[NSURL URLWithString:[kIMGURL stringByAppendingString:imageArr[index]]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image && cacheType == SDImageCacheTypeNone) {
                imageView.alpha = 0.0;
                [UIView transitionWithView:imageView
                                  duration:1.0
                                   options:UIViewAnimationOptionTransitionCrossDissolve
                                animations:^{
                                    [imageView setImage:image];
                                    imageView.alpha = 1.0;
                                } completion:NULL];
            }
        }];
    }
}

- (void)imagePlayerView:(ImagePlayerView *)imagePlayerView didTapAtIndex:(NSInteger)index
{
    
}

@end
